<template>
  <div>
    <div class="twui-astable xupload xsamll" v-show="imageUrl !== ''" v-if="!customtips">
      <div class="twui-imgzoombox twui-astable-col xupload-objbox">
        <div class="twui-imgzoom" :class="{xzoom:isZoom}" @click="isZoom=!isZoom">
          <img :src="imageUrl" />
        </div>
      </div>
    </div>
    <div class="twui-astable xupload xsamll">
      <div class="twui-astable-col">
        <el-upload
          :action="file_upload_server"
          :data="data"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :show-file-list="false"
          :accept="fileType"
          :disabled="disabled"
        >
          <button
            type="button"
            class="twui-btn xminor"
            slot="trigger"
            @click.prevent
            :disabled="disabled"
          >上传</button>
          <template v-if="customtips">
            <div style="display:flex">
              <img style="width:200px;height:112px;margin-top:7px;margin-right:10px" :src="imageUrl" v-show="imageUrl !== ''" />
              <img src="/ecoplatform/images/idcard.png" style="width:200px;height:112px;margin-top:7px;" v-if="showcase">
            </div>
            <slot></slot>
          </template>
          <div slot="tip" class="el-upload__tip" style="text-align:left;" v-else>只能上传jpg/png文件，且不超过2M</div>
        </el-upload>
      </div>
    </div>

    <!-- vueCropper 剪裁图片实现-->
    <el-dialog
      title="图片剪裁"
      :visible.sync="imgDialogVisible"
      :class="{ xzindex : imgDialogVisible }"
      ref="vueCropperDialog"
    >
      <div class="cropper-content">
        <div class="cropper" style="text-align: center;">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :info="true"
            :full="option.full"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :original="option.original"
            :autoCrop="option.autoCrop"
            :fixed="option.fixed"
            :fixedNumber="option.fixedNumber"
            :centerBox="option.centerBox"
            :infoTrue="option.infoTrue"
            :fixedBox="option.fixedBox"
          ></vueCropper>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="imgDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="finish" :loading="loading">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import props from './props'
import style from '../tw-lib-base/style'
import { VueCropper } from "vue-cropper"

export default {
  props: {
    initImageUrl: '',
    disabled: {
      type: Boolean,
      default: false
    },
    filesize: {
      type: String,
      default: '2'
    },
    customtips: {
      type: Boolean,
      default: false
    },
    showcase: {
      type: Boolean,
      default: false
    }
  },
  data () {
    var tenantId = this.$twApp.user.branchCode
    if (!tenantId || tenantId === 'null') {
      tenantId = 'PAAS01'
    }
    return {
      imageUrl: '',
      newImageUrl: '',
      fileUrl: '',
      fileType: '.jpeg,.jpg,.png',
      file_upload_server: this.$twApp.gateway + '/twasp/fs/fs/file/upload',
      isZoom: false,
      data: {
        branchCode: tenantId
      },
      imgDialogVisible: false,
      // 裁剪组件的基础配置option
      option: {
        img: "", // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: "jpeg", // 裁剪生成图片的格式
        canScale: false, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 100, // 默认生成截图框宽度
        autoCropHeight: 100, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [5, 5], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: true, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      picsList: [], // 页面显示的数组
      imageUrls: null,
      logoFile: null,
      loading: false
    }
  },
  watch: {
    initImageUrl (n) {
      if (this.initImageUrl) {
        this.imageUrl = this.$twApp.gateway + '/fs/media' + this.initImageUrl
      } else {
        this.imageUrl = ''
      }
    }
  },
  methods: {
    handleAvatarSuccess (res, file, filelist) {
      this.logoFile = res.fileInfos[0]
      this.option.img = this.$twApp.gateway + '/fs/media' + res.fileInfos[0].localPath // file.url
      this.imgDialogVisible = true
    },
    emitEvent (url) {
      if (url) {
        this.imageUrl = url
        this.initImageUrl = url
        var str = new RegExp("http");
        var str1 = new RegExp("https");
        if (str.test(this.initImageUrl) || str1.test(this.initImageUrl)) {
          this.imageUrl = url
        } else {
          this.imageUrl = this.$twApp.gateway + '/fs/media' + url
        }
      } else {
        this.imageUrl = ''
        this.initImageUrl = ''
      }
    },
    beforeAvatarUpload (file) {
      var allowTypes = 'image/jpeg,image/jpg,image/png'
      const isIMG = file.type !== '' && allowTypes.indexOf(file.type) !== -1
      let isLt2M = file.size / 1024 / 1024 < 2
      let errstring = "只能上传jpg/png文件，且不超过2M"
      if (this.filesize !== '2') {
        isLt2M = file.size / 1024 / 1024 < parseInt(this.filesize)
        errstring = "只能上传jpg/png文件，且大小不能超过要求"
      }
      if (!isIMG) {
        this.$message.error("只能上传jpg/png文件，且不超过2M")
      }
      if (!isLt2M) {
        this.$message.error(errstring)
      }
      return isIMG && isLt2M
    },
    // 点击裁剪，将裁剪后的图片上传到服务器并拿到服务器返回的的裁剪图片信息
    finish () {
      this.$refs.cropper.getCropBlob(data => {
        let formData = new FormData()
        formData.append('file', data)
        formData.append('branchCode', this.$twApp.user.branchCode ? this.$twApp.user.branchCode : 'PAAS01')

        window.axios({
          headers: { 'Content-Type': 'multipart/form-data' },
          url: this.file_upload_server,
          method: 'post',
          data: formData
        }).then(res => {
          this.logoFile = res.data.fileInfos[0]
          this.imgDialogVisible = false
          this.saveFile(this.logoFile)
          this.imageUrl = this.$twApp.gateway + '/fs/media' + this.logoFile.localPath
          this.fileUrl = res.data.fileInfos[0].localPath
          this.$emit('fileUrlChange', this.fileUrl, res.data.fileInfos[0].fileId)
        })
      })
    },
    saveFile: function (file) {
      var req = {}
      req.fileInfo = file
      if (this.$twApp.user.branchCode) {
        window.axios.post( this.$twApp.gateway + '/openapi-base/base/addFileInfo', req)
        .then(function (response) {
          response.data
        })
        .catch(function (error) {
          error.data
        })
      } else {
        // req.branchCode =  'PAAS01'
        window.axios({
          headers: { 'Tenant-Id': 'twsaas' },
          url: this.$twApp.gateway + '/openapi-base/base/addFileInfo',
          method: 'post',
          data: req
        })
        .then(function (response) {
          response.data
        })
        .catch(function (error) {
          error.data
        })
      }
    }
  },
  created(){
     if (this.initImageUrl) {
        this.imageUrl =  this.$twApp.gateway + '/fs/media' + this.initImageUrl
      } else {
        this.imageUrl = ''
      }
  },
  components: {
    VueCropper
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-upload {
  display: inline-block;
  text-align: center;
  cursor: pointer;
}
.cropper-content .cropper {
  width: auto;
  height: 300px;
}
</style>
